package com.example.cs342messenger;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;

import basicClasses.LoginObject;
import basicClasses.MessageObject;

import android.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import asyncTasks.GetMessages;

public class ConversationList extends Activity
{
	private ListView listview;
	Timer	timer;
	public static boolean		registerAcc	= false;
	private String user = "Bill";
	SharedPreferences mPrefs;
	static ArrayList<String> newMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_conversation_list);
		//populateList();
		new PopulateConversation().execute();
		timer = new Timer();
		TimerTask update = new timeTask();
		timer.scheduleAtFixedRate(update, 0, 30000);
		mPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
		user = mPrefs.getString("user", "NA");
		System.out.println("CONVERSATION LIST USER: " + user);
	    listview = (ListView) findViewById(R.id.listView1);
	    listview.setOnItemClickListener(new OnItemClickListener()
	    {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				String buddy =(String) parent.getItemAtPosition(position);
				//Toast.makeText(ConversationList.this, buddy, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(ConversationList.this, Messages.class);
				intent.putExtra("buddy", buddy);
				startActivity(intent);
			}
	    	
	    });
	    
	    final Button addContact = (Button) findViewById(R.id.addContactButton);
        addContact.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//add();
            	//Toast.makeText(ConversationList.this, "Clicked Add", Toast.LENGTH_SHORT).show();
            	EditText contact = (EditText) findViewById(R.id.addContactText);
            	String name = contact.getText().toString();
            	if(name.equals("")){
            		Toast.makeText(ConversationList.this, "Invalid Username", Toast.LENGTH_SHORT).show();
            	}else{
            		//check if it exists in mySql
            		URLHelper helper = new URLHelper();
            		String dir = "http://softeng.cs.uwosh.edu/students/cs342g6/exists.php?user="+name;
            		if(helper.retrieveTextData(dir)){
            			Intent intent = new Intent(ConversationList.this, Messages.class);
            			intent.putExtra("buddy", name);
            			contact.setText("");
            			startActivity(intent);
            		} else {
            			Toast.makeText(ConversationList.this, name+" does not exist", Toast.LENGTH_SHORT).show();
            		}
            	}
            	
            	
            }
        });
	    
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_conversation_list, menu);
		return true;
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if (registerAcc)
		{
			registerAcc = false;
			Intent intent = new Intent(this, Messages.class);
			startActivity(intent);
		}
		new PopulateConversation().execute();
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		if(item.getItemId() == R.id.menu_logout){
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putString("user", "");
			edit.putString("updates", "");
			edit.commit();
			LoginActivity.loggedIn = false;
			finish();
			return true;
		}else 
			return false;
	}

	public void populateList()
	{
		ListView lv = (ListView) findViewById(R.id.listView1);
		ArrayList<String> myList = new ArrayList<String>();
		myList.add("James");
		myList.add("Timmy");
		myList.add("Your Momma");
		myList.add("George \"Captain Awesome\" Thomas");
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, myList);
		lv.setAdapter(arrayAdapter);

		lv.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				String val =(String) parent.getItemAtPosition(position);
				Intent i = new Intent(ConversationList.this, Messages.class);
				// value.get(position)
				i.putExtra("reciever", val);
				startActivity(i);
			}

		});
		
		
		
	}
	
	
	
	

	public class timeTask extends TimerTask
	{

		private Handler	mHandler	= new Handler();

		@Override
		public void run()
		{
			// TODO Auto-generated method stub
			new Thread(new Runnable()
			{
				@Override
				public void run()
				{
					mHandler.post(new Runnable()
					{
						@Override
						public void run()
						{
							checkForMessages();
						}
					});
				}
			}).start();
		}

	}

	public void toastPop(int num)
	{
		if(num == 1){
			Toast.makeText(this, "New Message!", Toast.LENGTH_SHORT).show();
		}else if (num > 2){
			Toast.makeText(this, "New Messages!", Toast.LENGTH_SHORT).show();
		}
	}

	public void checkForMessages(){
		String consToUpdate = "";
		LoginObject log = new LoginObject(user, "");
		ArrayList<MessageObject> messages = new ArrayList<MessageObject>();
		try {
			messages = new GetMessages().execute(log).get();
			consToUpdate = mPrefs.getString("updates","");
			for(int i = 0; i < messages.size(); i++){
				MessageObject m = messages.get(i);
				if(!m.getSender().equals("NOBODY")){
					toastPop(messages.size());
					consToUpdate = consToUpdate + " " + m.getSender();
					Comment c = new Comment();
					c.setUser(m.getSender());
					c.setReciever(m.getReciever());
					c.setComment(m.getText());
					DatabaseConnector db = new DatabaseConnector(this);
					db.open();
					db.enterMessage(c);
					db.close();
				}
			}
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putString("updates", consToUpdate);
			edit.commit();
			new PopulateConversation().execute();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	private class PopulateConversation extends AsyncTask<String, Object, List<Comment>>
	{
	private DatabaseConnector dbAdapter = new DatabaseConnector(ConversationList.this);
		
		
		@Override
		protected List<Comment> doInBackground(String...objects){
			dbAdapter.open();
			return dbAdapter.populateContacts(user);
			
		}
		
		protected void onPostExecute(List<Comment> result)
		{			
	  		ListView listView;
	  		//Toast.makeText(ConversationList.this, result.get(0).getComment(), Toast.LENGTH_SHORT).show();
	  		listView = (ListView) findViewById(R.id.listView1);
	  		ArrayList<String> myList = new ArrayList<String>();
	  		for(int i=0; i < result.size(); i++){
	  			myList.add(result.get(i).getUser());
	  		}
	  		
	  		newMessage = new ArrayList<String>();
	  		
	  		String toUpdate = mPrefs.getString("updates", "none");
	  		//System.out.println(toUpdate);
	  		if(!toUpdate.equals("none")){
	  			String delims = "[ ]+";
	  			String[] update = toUpdate.split(delims);
	  			for(int i = 0; i < update.length; i++){
	  				//System.out.println(update[i]);
	  				if(!update.equals("") && !update.equals(" ") && !update.equals(user)){
	  					newMessage.add(update[i]);
	  				}
	  			}
	  		}
	  		
	  		/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(ConversationList.this,
				android.R.layout.simple_list_item_1, myList);*/
	  		ArrayAdapter<String> adapter = new ConversationListViewAdapter(ConversationList.this, R.layout.activity_conversation_list, myList);
	  		//adapter = new MessageListViewAdapter(ConversationList.this, R.layout.activity_messages, result);
	  		listView.setAdapter(adapter);

	  		/*String toUpdate = mPrefs.getString("updates", "Bill");
	  		if(!toUpdate.equals("none")){
	  			String delims = "[ ]+";
	  			String[] update = toUpdate.split(delims);
	  			ListAdapter lv = listView.getAdapter();
		  		int childCount = lv.getCount();
		  	    for (int i = 0; i < childCount; i++)
		  	    {
		  	        View v = (View) lv.getItem(i);
		  	        int vid = (int)lv.getItemId(i);
		  	        TextView tx = (TextView) v.findViewById(vid);
		  	        boolean isThere = false;
		  	        for(int j = 0; j < update.length; j++){
		  	        	if(tx.getText().toString().equals(update[j])){
		  	        		isThere = true;
		  	        	}
		  	        }
		  	        if(isThere){
		  	        	tx.setBackgroundColor(0xFF00FF00);
		  	        }
		  	    }
	  		}*/

			dbAdapter.close();
		}

	}
}
